<template>
  <el-container class="survey-outer">
    <el-container>
      <el-aside class="placeholder" id="no">
        <div class="q-box">
          <el-tabs v-model="activeName" type="card" stretch>
            <el-tab-pane label="题库" name="questions"></el-tab-pane>
            <el-tab-pane label="问卷大纲" name="outline"></el-tab-pane>
          </el-tabs>
          <div v-if="activeName==='questions'">
            <ul>
              <li v-for="(question,index) in questionTypes" :key="index" @click="onAddQuestion(question)"
                class="type-item">
                {{question.label}}</li>
            </ul>
          </div>
          <div v-else>
            <SlickList lockAxis="y" v-model="surveyPage.Questions" :lockToContainerEdges="true" :pressDelay="200">
              <SlickItem v-for="(item, index) in surveyPage.Questions" :index="index" :key="index" class="type-item">
                <div @click="scrollToItem(index)">
                  {{index+1}}.{{ item.title }}
                </div>
              </SlickItem>
            </SlickList>
          </div>
        </div>
      </el-aside>
      <el-main class="placeholder survey-body">
        <div class="testpdf">
          <input type="button" @click="printDiv" value="点击打印为PDF文件" id="button">
          <div id="div_print">
            <h1 id="main-no">问卷主体</h1>
            <el-input v-model="surveyPage.QName" placeholder="请输入问卷名称"
              style="margin:10px auto;text-align:center;width:30%"></el-input>
            <el-input v-model="surveyPage.Qdescription" placeholder="请输入问卷描述"
              style="margin:10px auto;text-align:center;width:80%"></el-input>
            <ul>
              <li :key="index" v-for="(item,index) in surveyPage.Questions" class="q-item" :id="'qitem'+index">
                <!-- 展示题面 -->
                <div v-if="item.masked" v-on:click="item.masked=false" style="display:flex">
                  <!-- 题号显示 -->
                  <span style="margin-top:6px;font-weight:bold;height:100%"
                    v-show="surveyPage.autoOrder">{{index+1}}.</span>
                  <!-- 题面 -->
                  <component v-bind:is="itemTypeTransformer(item.type)" :question="item" :options="surveyOptions"
                    :showMax="true">
                  </component>
                </div>
                <!-- 编辑器 -->
                <div v-else>
                  <component :is="editorTypeTransformer(item.type)" :setting="item"
                    @change="onChangeQuestion($event,index)" @cancel="item.masked=true" :options="surveyOptions">
                  </component>
                </div>
                <!-- 操作分割符 -->
                <el-divider></el-divider>
                <!-- 操作 -->
                <div class="question-action" :id="index">
                  <el-button @click="moveUp(index) " :disabled="index===0">上移</el-button>
                  <el-button @click="moveDown(index)" :disabled="index === surveyPage.Questions.length-1">下移</el-button>
                  <el-button type="danger" @click="removeQuestion(index)">删 除</el-button>
                </div>
              </li>
            </ul>
          </div>
        </div>
      </el-main>
      <el-aside class="placeholder" id="no1">
        <div class="right-box">
          <h1>状态栏</h1>
          <el-divider>问卷设置</el-divider>
          <el-switch :active-value="1" :inactive-value="0" active-text="重复填写" inactive-text="单次填写"
            v-model="surveyPage.Repeat"></el-switch>
          <el-switch active-text="显示题序" inactive-text="关闭题序" v-model="surveyPage.autoOrder"></el-switch>
          <el-switch active-text="随机顺序" inactive-text="相同顺序" v-model="surveyPage.is_shuffled"
            v-if="surveyPage.type=='exam'"></el-switch>
          <el-switch active-text="自动截止" inactive-text="手动截止" v-model="surveyPage.autoStop"></el-switch>
          <el-date-picker type="datetime" v-model="surveyPage.ETime" v-if="surveyPage.autoStop"
            value-format="yyyy-MM-dd HH:mm:ss"></el-date-picker>
          <el-switch active-text="数量限制" inactive-text="数量无限制" v-model="limitSurvey"></el-switch>
          <div>
            <el-input-number v-model="surveyPage.count" v-if="limitSurvey" :min="0"></el-input-number>
          </div>
          <el-button type="primary" @click="saveOption" v-if="this.QID>0" style="margin:10px">保存设置</el-button>
        </div>
      </el-aside>
    </el-container>
    <el-footer class="placeholder" id="no2">
      <el-button type="primary" style="fixed" @click="saveSurvey">保存题目</el-button>
    </el-footer>
  </el-container>
</template>
<script>
import QitemCheckbox from "../components/Item/QitemCheckbox.vue";
import QitemRadio from "../components/Item/QitemRadio.vue";
import QitemRate from "../components/Item/QitemRate.vue";
import QitemTextBlank from "../components/Item/QitemTextBlank.vue";
import QuestionBox from "../components/QuestionBox.vue";
import QeditorRadio from "../components/Editor/QeditorRadio.vue";
import QeditorCheckbox from "@/components/Editor/QeditorCheckbox";
import QeditorRate from "@/components/Editor/QeditorRate";
import QeditorTextBlank from "@/components/Editor/QeditorTextBlank";
import { SlickList, SlickItem } from "vue-slicksort";
import QeditorLocation from "../components/Editor/QeditorLocation.vue";
import QitemLocation from "../components/Item/QitemLocation.vue";
export default {
  components: {
    QuestionBox,
    QitemCheckbox,
    QitemRadio,
    QitemRate,
    QitemTextBlank,
    QeditorRadio,
    QeditorTextBlank,
    QeditorRate,
    QeditorCheckbox,
    SlickList,
    SlickItem,
    QeditorLocation,
    QitemLocation
  },
  Answername: "SurveyPage",
  data() {
    return {
      activeName: "questions",
      questionTypes: [
        { type: "single", label: "单选题" },
        { type: "multi", label: "多选题" },
        { type: "blank", label: "填空题" },
        { type: "rate", label: "评分题" },
        { type: "location", label: "位置题" }
      ],
      surveyPage: {
        count: -1
      },
      limitSurvey: false,
      surveyOptions: {},
      QID: -1
    };
  },
  methods: {
    saveOption() {
      var op = {
        // ...
        QID: this.QID,
        autoOrder: this.surveyPage.autoOrder, //自动插入题号
        is_shuffled: this.surveyPage.is_shuffled, //乱序
        autoStop: this.surveyPage.autoStop, //自动截止
        ETime: this.surveyPage.ETime,
        Repeat: this.surveyPage.Repeat, //重复填写
        count: this.limitSurvey == true ? this.surveyPage.count : -1
        // ...
      };
      this.$serve
        .saveOption(op)
        .then(res => {
          this.$message.success("修改设置成功");
        })
        .catch(err => {
          this.$message.error("修改设置失败");
        });
    },
    printDiv() {
      for (var i = 0; i < this.surveyPage.Questions.length; i++) {
        document.getElementById(i).style.display = "none";
      }
      document.getElementsByClassName("el-header")[0].style.display = "none"; //不需要打印的部分隐藏
      document.getElementsByClassName("el-header")[1].style.display = "none"; //不需要打印的部分隐藏
      document.getElementById("no").style.display = "none"; //不需要打印的部分隐藏
      document.getElementById("no1").style.display = "none";
      document.getElementById("no2").style.display = "none";
      document.getElementById("main-no").style.display = "none";
      document.getElementById("button").style.display = "none";
      window.print();
      document.getElementById("main-no").style.display = "block";
      document.getElementById("no").style.display = "block"; //恢复打印前的页面
      document.getElementById("no1").style.display = "block"; //恢复打印前的页面
      document.getElementById("no2").style.display = "block"; //恢复打印前的页面
      document.getElementById("button").style.display = "block"; //恢复打印前的页面
      document.getElementsByClassName("el-header")[0].style.display = "block";
      document.getElementsByClassName("el-header")[1].style.display = "block";
      for (var i = 0; i < this.surveyPage.Questions.length; i++) {
        document.getElementById(i).style.display = "block";
      }
      return false;
    },
    scrollToItem(index) {
      this.$nextTick(() => {
        document
          .getElementById("qitem" + index)
          .scrollIntoView({ behavior: "smooth" });
      });
    },
    moveUp(index) {
      let arr = this.surveyPage.Questions;
      arr.splice(index - 1, 1, ...arr.splice(index, 1, arr[index - 1]));
    },
    moveDown(index) {
      let arr = this.surveyPage.Questions;
      arr.splice(index, 1, ...arr.splice(index + 1, 1, arr[index]));
    },
    checkEdit() {
      for (let item of this.surveyPage.Questions) {
        if (item.masked == false) return false;
      }
      return true;
    },
    saveSurvey() {
      // 根据问卷创建/编辑来决定提交端口
      if (this.checkEdit()) {
        if (this.surveyPage.Questions.length == 0)
          this.$message.error("请至少添加一题");
        else {
          this.surveyPage.count =
            this.limitSurvey == true ? this.surveyPage.count : -1;
          this.QID <= -1 ? this.submitSurvey() : this.modifySurvey();
        }
      } else {
        this.$message.warning("部分题目处于编辑状态");
      }
    },
    submitSurvey() {
      this.$serve
        .submitSurveyPage(this.surveyPage)
        .then(res => {
          this.$router.replace("/manage");
          this.$message.success("保存问卷成功");
        })
        .catch(err => {
          if (err.status == 412) this.$message.error("不能有同名问卷");
          else this.$message.error("保存问卷失败");
        });
    },
    modifySurvey() {
      this.$confirm("是否保留已回收问卷？", "提示", {
        confirmButtonText: "保留",
        cancelButtonText: "不保留",
        type: "warning"
      })
        .then(() => {
          this.surveyPage.Djudge = false;
          this.$serve
            .modifySurveyPage(this.surveyPage)
            .then(res => {
              this.$message.success("保存问卷成功");
            })
            .catch(err => {
              if (err.status == 412) this.$message.error("不能有同名问卷");
              else this.$message.error("保存问卷失败");
            });
        })
        .catch(() => {
          this.surveyPage.Djudge = true;
          this.$serve
            .modifySurveyPage(this.surveyPage)
            .then(res => {
              this.$message.success("保存问卷成功");
            })
            .catch(err => {
              if (err.status == 412) this.$message.error("不能有同名问卷");
              else this.$message.error("保存问卷失败");
            });
        });
    },
    initTemplate() {
      //为不同种类的问卷添加题目
      let type = this.surveyPage.type;
      if (type == "vote") {
        this.surveyPage.Questions = this.$mTool.initVote();
      } else if (type == "sign") {
        this.surveyPage.Questions = this.$mTool.initSign();
      } else if (type == "exam") {
        this.surveyPage.Questions = this.$mTool.initExam();
      } else if (type == "location") {
        this.surveyPage.Questions = this.$mTool.initLocation();
      }
    },
    initOptions() {
      // 根据问卷类型选择题目类型
      this.surveyOptions = this.$mTool.initOptions(this.surveyPage.type);
    },
    initSurvey() {
      // 此处新建问卷
      var obj = {
        is_shuffled: false,
        autoOrder: true,
        collectNumber: 0,
        Djudge: false,
        // createTime: "2020-02-20 20:20:20",
        // publishTime: "2020-02-20 20:20:20",
        autoStop: false,
        ETime: "",
        QID: -1,
        issuer: this.$store.state.userName,
        QName: "新建问卷",
        Qdescription: "我是一只问卷",
        status: 0,
        Repeat: 1,
        type: "sign",
        Questions: [],
        count: -1
      };
      switch (this.QID) {
        case "-1":
          obj.QName = "新建普通问卷";
          obj.type = "normal";
          break;
        case "-2":
          obj.QName = "新建投票问卷";
          obj.type = "vote";
          break;
        case "-3":
          obj.QName = "新建报名问卷";
          obj.type = "sign";
          break;
        case "-4":
          obj.QName = "新建考试问卷";
          obj.type = "exam";
          break;
        case "-5":
          obj.QName = "新建疫情打卡问卷";
          obj.type = "location";
          break;
      }
      // 此处为特别问卷添加题目
      this.surveyPage = obj;
      this.initTemplate();
      this.initOptions();
      this.$message.info("新建问卷");
    },
    getSurveyPage() {
      // 此处向后端请求问卷
      // 由于后端格式过于呆瓜，必须修改
      this.$serve
        .getSurveyPage(this.QID)
        .then(res => {
          if (res.data.issuer != this.$store.state.userName) {
            this.$message("您无权限修改此问卷");
            this.$router.replace("/Manage");
          }
          var arr = [];
          for (let item of res.data.Questions) {
            arr.push(Object.assign(item, { masked: true }));
          }
          this.surveyPage = res.data;
          this.surveyPage.Questions = arr;
          this.limitSurvey = this.surveyPage.count == -1 ? false : true;
          this.initOptions();
          this.$message.success("成功加载问卷：" + this.surveyPage.QName);
        })
        .catch(err => {
          this.$message.error("加载问卷失败");
        });
    },
    onChangeQuestion(newVal, index) {
      console.log(newVal);
      newVal.masked = true;
      this.$set(this.surveyPage.Questions, index, newVal);
      console.log(this.surveyPage.Questions);
    },
    removeQuestion(index) {
      if (this.surveyPage.Questions.length > 0)
        this.surveyPage.Questions.splice(index, 1);
      else this.$message.error("至少保留一题");
    },
    onAddQuestion(qitem) {
      var newItem = this.$mTool.creatNewQuestion(
        qitem.type,
        this.surveyPage.type
      );
      this.$message.success("添加问题成功");
      this.surveyPage.Questions.push(newItem);
    },
    itemTypeTransformer(qtype) {
      return this.$mTool.itemTypeTransformer(qtype);
    },
    editorTypeTransformer(qtype) {
      return this.$mTool.editorTypeTransformer(qtype);
    }
  },
  watch: {
    $route(newVal, oldVal) {
      this.QID = newVal.params.QID;
    }
  },
  mounted() {
    this.QID = this.$route.params.QID;
    if (this.QID <= -1) {
      this.initSurvey();
    } else {
      this.getSurveyPage();
    }
  }
};
</script>
<style media="print">
@page {
  size: auto; /* auto is the initial value */
  margin: 0mm; /* this affects the margin in the printer settings */
}
</style>
<style scoped>
@media print {
  .q-item {
    box-shadow: none !important;
    border: none;
  }
  .q-item:hover {
    box-shadow: none !important;
  }
  #div_print >>> .el-input__inner {
    border: 0;
    text-align: center;
    font-weight: 600;
  }
}
#button {
  width: 100%;
  /* background-color: aquamarine; */
  background-color: transparent;
  display: block;
  text-align: right;
  border: none;
  color: red;
  cursor: pointer;
  font-size: 15px;
}
.q-box {
  position: fixed;
  left: 3%;
  padding: 20px;
  padding-bottom: 100px;
  min-width: 250px;
  /* height: 90%; */
  max-height: 500px;
  /* min-height: 340px; */
  overflow: auto;
  margin: 0 auto;
  top: 145px;
  box-sizing: border-box;
  background-color: #fff;
  box-shadow: 0 2px 12px 0 rgb(0 0 0 / 10%);
  border: 1px solid #fff;
  z-index: 3;
}
.q-box li {
  list-style: none;
}
/deep/ .el-tabs__item {
  font-size: 20px;
  color: #222;
  font-weight: 500;
}
.type-item {
  margin: 10px auto;
  padding: 10px;
  width: 70%;
  border: 1px dashed rgba(24, 144, 255, 0.05);
  background: rgba(24, 144, 255, 0.05);
  font-size: 18px;
}
/deep/ .el-tabs__item.is-active {
  color: #409eff;
}
.type-item:hover {
  color: #409eff;
  cursor: pointer;
  border: 1px dashed #1890ff;
}
.survey-outer {
  background-color: white;
}
.survey-body {
  min-height: 700px;
}
.placeholder {
  position: relative;
  background-color: white;
  margin-right: 10px;
  border: none;
}
.q-subnav {
  width: 300px;
}
.q-item {
  /* border: solid 1px #333;
  border-radius: 30px;
  padding: 10px;
  margin: 10px; */
  margin: 10px auto;
  padding: 10px;
  width: 98%;
  border: 1px dashed rgba(24, 144, 255, 0.05);
  background: rgba(24, 144, 255, 0.05);
  font-size: 18px;
}
.q-item:hover {
  /* background-color:white ; */
  /* border:1px dashed white; */
  box-shadow: 0 2px 7px 0 rgb(0 0 0 / 10%);
  /* background: rgb(154, 157, 158); */
  cursor: pointer;
}
.right-box {
  position: fixed;
  padding: 5px;
  right: 3%;
  padding: 20px;
  padding-bottom: 100px;
  min-width: 250px;
  max-height: 500px;
  overflow: auto;
  /* height: 90%; */
  margin: 0 auto;
  top: 150px;
  box-sizing: border-box;
  background-color: #fff;
  box-shadow: 0 2px 12px 0 rgb(0 0 0 / 10%);
  border: 1px solid #fff;
  z-index: 3;
}
.right-box h1 {
  width: 97px;
  height: 39px;
  line-height: 39px;
  text-align: center;
  display: block;
  margin: 0 auto;
  font-size: 20px;
  color: #222;
  font-weight: 500;
}
.el-switch {
  margin: 10px auto;
  padding: 10px;
  width: 80%;
  border: 1px dashed rgba(24, 144, 255, 0.05);
  background: rgba(24, 144, 255, 0.05);
  font-size: 5px;
  height: 30px;
  line-height: 30px;
  display: flex;
  justify-content: space-between;
}
/deep/ .el-switch__label {
  height: 30px;
  display: flex;
  align-items: center;
  /* vertical-align: top; */
}
ul li {
  list-style: none;
}
.status {
  text-align: left;
  padding-left: 20px;
}
.main-title {
  padding: 6px 10px;
  border: 1px dashed transparent;
  line-height: 30px;
  margin: 0;
  font-size: 25px;
  font-weight: bold;
  color: #25262b;
}
/* .el-tag{
  width:100px;
  display: inline-block;
} */
.question-action {
  display: flex;
  /* flex-flow:column; */
  justify-content: left;
  margin-top: 15px;
  /* position:absolute; */
  /* bottom:0;
  right:0; */
}
</style>